import { Response } from 'express';
import { AuthenticatedRequest } from '@/middleware/auth';
import { OilPriceService } from '@/services/oilPriceService';
import { OilPriceQuery, OilPriceUpdateRequest } from '@/types/oilPrice';

/**
 * @swagger
 * /api/oil-prices:
 *   get:
 *     summary: 获取油价数据
 *     tags: [油价]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: province
 *         schema:
 *           type: string
 *         description: 省份筛选
 *       - in: query
 *         name: fuelType
 *         schema:
 *           type: string
 *           enum: ['92', '95', '98', '0']
 *         description: 燃油类型筛选
 *       - in: query
 *         name: latest
 *         schema:
 *           type: boolean
 *           default: true
 *         description: 是否只显示最新数据
 *     responses:
 *       200:
 *         description: 获取成功
 *       500:
 *         description: 服务器内部错误
 */
export const getOilPrices = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { province, fuelType, latest = 'true' } = req.query as OilPriceQuery;
    const isLatest = latest === 'true';

    const oilPriceService = OilPriceService.getInstance();
    const oilPrices = await oilPriceService.getOilPrices(province, isLatest);

    // 如果指定了燃油类型，进行过滤
    let filteredPrices = oilPrices;
    if (fuelType) {
      filteredPrices = oilPrices.filter(price => {
        switch (fuelType) {
          case '92':
            return price.price92 > 0;
          case '95':
            return price.price95 > 0;
          case '98':
            return price.price98 > 0;
          case '0':
            return price.price0 > 0;
          default:
            return true;
        }
      });
    }

    res.status(200).json({
      success: true,
      message: '获取油价数据成功',
      data: filteredPrices,
      lastUpdate: oilPriceService.getLastUpdateTime(),
      totalCount: filteredPrices.length,
    });
  } catch (error) {
    console.error('获取油价数据失败:', error);
    res.status(500).json({
      success: false,
      message: '获取油价数据失败',
      error: error instanceof Error ? error.message : '未知错误',
    });
  }
};

/**
 * @swagger
 * /api/oil-prices/statistics:
 *   get:
 *     summary: 获取油价统计信息
 *     tags: [油价]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 获取成功
 *       500:
 *         description: 服务器内部错误
 */
export const getOilPriceStatistics = async (
  _req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const oilPriceService = OilPriceService.getInstance();
    const statistics = await oilPriceService.getOilPriceStatistics();

    res.status(200).json({
      success: true,
      message: '获取油价统计信息成功',
      data: statistics,
    });
  } catch (error) {
    console.error('获取油价统计信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取油价统计信息失败',
      error: error instanceof Error ? error.message : '未知错误',
    });
  }
};

/**
 * @swagger
 * /api/oil-prices/update:
 *   post:
 *     summary: 手动更新油价数据
 *     tags: [油价]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: false
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               force:
 *                 type: boolean
 *                 description: 是否强制更新
 *               source:
 *                 type: string
 *                 description: 指定数据源
 *     responses:
 *       200:
 *         description: 更新成功
 *       400:
 *         description: 请求参数错误
 *       500:
 *         description: 服务器内部错误
 */
export const updateOilPrices = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { force = false, source: _source } = req.body as OilPriceUpdateRequest;

    const oilPriceService = OilPriceService.getInstance();

    // 检查更新状态
    if (oilPriceService.getUpdateStatus() && !force) {
      res.status(400).json({
        success: false,
        message: '油价数据正在更新中，请稍后再试',
      });
      return;
    }

    const updatedCount = await oilPriceService.updateOilPrices(force);

    res.status(200).json({
      success: true,
      message: '油价数据更新成功',
      data: {
        updatedCount,
        totalCount: updatedCount,
        updateTime: new Date(),
        nextUpdateTime: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24小时后
      },
    });
  } catch (error) {
    console.error('更新油价数据失败:', error);
    res.status(500).json({
      success: false,
      message: '更新油价数据失败',
      error: error instanceof Error ? error.message : '未知错误',
    });
  }
};

/**
 * @swagger
 * /api/oil-prices/status:
 *   get:
 *     summary: 获取油价服务状态
 *     tags: [油价]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 获取成功
 */
export const getOilPriceStatus = async (
  _req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const oilPriceService = OilPriceService.getInstance();

    res.status(200).json({
      success: true,
      message: '获取油价服务状态成功',
      data: {
        isUpdating: oilPriceService.getUpdateStatus(),
        lastUpdateTime: oilPriceService.getLastUpdateTime(),
        nextUpdateTime: oilPriceService.getLastUpdateTime()
          ? new Date(
              oilPriceService.getLastUpdateTime()!.getTime() +
                24 * 60 * 60 * 1000
            )
          : null,
      },
    });
  } catch (error) {
    console.error('获取油价服务状态失败:', error);
    res.status(500).json({
      success: false,
      message: '获取油价服务状态失败',
      error: error instanceof Error ? error.message : '未知错误',
    });
  }
};

/**
 * @swagger
 * /api/oil-prices/search:
 *   get:
 *     summary: 搜索油价数据
 *     tags: [油价]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: keyword
 *         schema:
 *           type: string
 *         description: 搜索关键词（省份名称）
 *       - in: query
 *         name: minPrice
 *         schema:
 *           type: number
 *         description: 最低价格
 *       - in: query
 *         name: maxPrice
 *         schema:
 *           type: number
 *         description: 最高价格
 *     responses:
 *       200:
 *         description: 搜索成功
 *       500:
 *         description: 服务器内部错误
 */
export const searchOilPrices = async (
  req: AuthenticatedRequest,
  res: Response
): Promise<void> => {
  try {
    const { keyword, minPrice, maxPrice } = req.query;

    const oilPriceService = OilPriceService.getInstance();
    let oilPrices = await oilPriceService.getOilPrices(undefined, true);

    // 关键词搜索
    if (keyword) {
      oilPrices = oilPrices.filter(price =>
        price.province.toLowerCase().includes((keyword as string).toLowerCase())
      );
    }

    // 价格范围筛选
    if (minPrice || maxPrice) {
      oilPrices = oilPrices.filter(price => {
        const min = minPrice ? parseFloat(minPrice as string) : 0;
        const max = maxPrice ? parseFloat(maxPrice as string) : Infinity;

        return (
          (price.price92 >= min && price.price92 <= max) ||
          (price.price95 >= min && price.price95 <= max) ||
          (price.price98 >= min && price.price98 <= max) ||
          (price.price0 >= min && price.price0 <= max)
        );
      });
    }

    res.status(200).json({
      success: true,
      message: '搜索油价数据成功',
      data: oilPrices,
      totalCount: oilPrices.length,
    });
  } catch (error) {
    console.error('搜索油价数据失败:', error);
    res.status(500).json({
      success: false,
      message: '搜索油价数据失败',
      error: error instanceof Error ? error.message : '未知错误',
    });
  }
};
